<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>高校社团管理系统</h2>
        </div>
      </template>

      <el-form :model="loginForm" :rules="rules" ref="loginFormRef">
        <el-form-item prop="email">
          <el-input
              v-model="loginForm.email"
              placeholder="请输入邮箱"
              prefix-icon="Message">
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password>
          </el-input>
        </el-form-item>

        <el-form-item prop="checkCode">
          <div class="check-code-container">
            <el-input
                v-model="loginForm.checkCode"
                placeholder="请输入验证码"
                style="width: 200px">
            </el-input>
            <img
                :src="checkCodeImage"
                @click="refreshCheckCode"
                class="check-code-image"
                alt="验证码">
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleLogin" style="width: 100%">登录</el-button>
        </el-form-item>

        <div class="login-footer">
          <span>还没有账号？</span>
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loginFormRef = ref(null)
const checkCodeImage = ref('')
const checkCodeKey = ref('')

const loginForm = reactive({
  email: '',
  password: '',
  checkCode: '',
  checkCodeKey: ''
})

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  checkCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
}

// 获取验证码
const getCheckCode = async () => {
  try {
    const res = await axios.get('/account/checkCode')
    if (res.data.status === 'success') {
      checkCodeImage.value = res.data.data.checkCode
      loginForm.checkCodeKey = res.data.data.checkCodeKey
    }
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}

// 刷新验证码
const refreshCheckCode = () => {
  getCheckCode()
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await axios.post('/account/login', loginForm)
        if (res.data.status === 'success') {
          // 改回使用 localStorage 存储登录信息
          localStorage.setItem('token', res.data.data.token)
          localStorage.setItem('userInfo', JSON.stringify(res.data.data))
          
          ElMessage.success('登录成功')
          const redirect = router.currentRoute.value.query.redirect || '/home'
          router.push(redirect)
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.info || '登录失败')
        refreshCheckCode()
      }
    }
  })
}

onMounted(() => {
  getCheckCode()
})
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
}

.check-code-container {
  display: flex;
  gap: 10px;
}

.check-code-image {
  height: 32px;
  cursor: pointer;
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}
</style>